package sensimulator.intersection.lanes;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.util.Date;
import java.util.HashMap;

import javax.print.attribute.standard.DateTimeAtCompleted;

import sennetworkserver.LaneStore;
import sennetworkserver.TrafficLight;
import sensimulator.intersection.Intersection;
import sensimulator.intersection.traffic.Car;
import sensimulator.intersection.traffic.Cyclists;

public class CyclistLane extends Lane {

	static final int BLINK_INTERVAL		= 1000;
	static final String LIGHT_RED		= "resources/light_red_small.png";
	static final String LIGHT_ORANGE	= "resources/light_green_small.png";
	static final String LIGHT_GREEN		= "resources/light_green_small.png"; 
	static final String LIGHT_OFF		= "resources/light_off_small.png"; 
	
	private HashMap<Integer, Image> lightImages;
	
	private boolean blink;
	
	private long lastChange;
	
	public CyclistLane(int laneId, Intersection intersection) {
		this(laneId, intersection, true);
	}
	
	public CyclistLane(int laneId, Intersection intersection, boolean receivesUpdates) {
		super(laneId, intersection, receivesUpdates);
	
		lastChange = new Date().getTime();
		lightImages = new HashMap<Integer, Image>();
		lightImages.put(TrafficLight.OFF,		Toolkit.getDefaultToolkit().createImage(LIGHT_OFF));
		lightImages.put(TrafficLight.RED,		Toolkit.getDefaultToolkit().createImage(LIGHT_RED));
		lightImages.put(TrafficLight.ORANGE,	Toolkit.getDefaultToolkit().createImage(LIGHT_ORANGE));
		lightImages.put(TrafficLight.GREEN,		Toolkit.getDefaultToolkit().createImage(LIGHT_GREEN));
	}

	public void spawnTraffic(boolean triggerSensor) {
		synchronized (traffic) { 
			addTraffic(new Cyclists(this, getFirstNode().getPoint())); 
			
			if (triggerSensor)
				LaneStore.getLane(getId()).getSensor100m().notifyObservers(false);
		}
	}
	
	public void paint(Graphics g, ImageObserver imageObserver) {
		Graphics2D g2 = (Graphics2D) g;
		
		int state = LaneStore.getLane(laneId).getTrafficLight().getState();
		Image lightImage = lightImages.get(state);
		
		for (TrafficLightNode light : trafficLights) {
			AffineTransform t = new AffineTransform();
			
			t.translate(light.getPoint().x, light.getPoint().y);
			t.rotate(-Math.toRadians(light.getRotation()));
			
			g2.setTransform(t);	
			g2.drawImage(blink ? lightImage : lightImages.get(TrafficLight.OFF), 
									 -lightImage.getWidth(imageObserver) / 2, 
								     -lightImage.getHeight(imageObserver) / 2, imageObserver);
		}
		
		if (state == TrafficLight.ORANGE) {
			long time = new Date().getTime();
			if (time - lastChange >= BLINK_INTERVAL) {
				lastChange = time;
				blink = !blink;
			}
		} else
			blink = true;
		
		g2.setTransform(new AffineTransform());
	}
}
